import re
from rest_framework.views import APIView
import hashlib, time
import logging
import json
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from django.core import serializers

logger = logging.getLogger('log')
from django.http import JsonResponse
# 只能用相对路径 绝对路径会报错
from ..models import ptUser
from ..serverEvCfg import httpResponseSignal


def md5_salt(txt,index):
    '''
    MD5 加密
    :return:
    '''
    nowTime = str(time.time())
    # 加密token
    if(index == 2):
        md5Txt = hashlib.md5(bytes(txt + 'wzy', encoding='UTF8'))
        md5Txt.update(bytes(nowTime, encoding='utf8'))
    # 加密password

    if(index == 1):
        md5Txt = hashlib.md5(bytes(txt + 'wzy', encoding='UTF8'))

    return md5Txt.hexdigest()


class loginView(APIView):
    '''
    用户登录接口
    '''
    authentication_classes = [] # 禁用认证组件
    def post(self, request): # POST 支持POST 不支持GET  在APIView可以看到对应的信息
        data = {}
        data["data"] = {}
        try:
            # {"username":"root","password":"a2932623"}
            # {data: "{"username":"root","password":"a2932623"}"}
             # b'{"data":"{\\"username\\":\\"root\\",\\"password\\":\\"a2932623\\"}"}'
            json_data= eval(json.loads(request.body)["data"])
            #  eval 用来去除request.body中的转义字符

            un = json_data["username"]
            pw = md5_salt(json_data["password"],1)


            result = ptUser.objects.filter(user_name=un, user_password=pw)
            print('--->',ptUser)
            if result:
                token = md5_salt(un,2)
                ptUser.objects.update_or_create(user_id=result.values('user_id')[0]['user_id'],
                                                defaults={'token': token})
                data["data"]['token'] = token
                data["data"]['uuid'] = result.values("user_id")[0]["user_id"]
                data["data"]['uname'] = result.values("user_account")[0]["user_account"]
                data["data"]['type'] = result.values("user_type")[0]["user_type"]
                # 成功
                data["status"] = "Success"
                data["message"]="登陆成功"
                data["code"] = 200
            else:
                # 错误
                data['error'] = 1
                data['status'] = "Success"
                data['message'] = '用户名或者密码错误'
                data['code'] = 201
        except EOFError as e:
            # 异常
            logging.error(e)
            data['error'] = 1
            data['status'] = "fail"
            data['message'] = '异常'
            data['code'] = 500
        return JsonResponse(data)

@csrf_exempt # 允许跨域
@api_view(["POST"]) #
def addAlterUser(request):
    '''
    x新增/修改用户
    '''
    data = json.loads(request.body)
    try:
        pw = md5_salt(data["password"],1)
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        if data["id"] == "":# 用户name已存在
            userData = ptUser.objects.filter(user_name=data["name"])
            if list(userData) !=[]:
                response = httpResponseSignal.httpResponseSignal().getFail()
                response["msg"] = "当前用户已存在"
            else: # 不存在，则新增用户
                ptUser(user_name=data["name"], user_account=data["user_account"], user_password=pw,
                            user_type=data["user_type"]).save()
                response["msg"] = "新增成功"
        else:
            userList = ptUser.objects.get(user_id=data["id"])

            userList.user_name = data["name"] #
            userList.user_account = data["user_account"]
            userList.user_password = pw
            userList.user_type = data["user_type"]
            userList.save()
            response["msg"] = "修改成功"
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)
        response = httpResponseSignal.httpResponseSignal().getFail()
        response["msg"] = "添加失败，请联系管理员"
        return JsonResponse(response)

@csrf_exempt # 允许跨域
@api_view(["POST"]) #
def getUserData(request):
    '''
    获取单个用户信息
    '''
    data = json.loads(request.body)
    try:
        userData = ptUser.objects.filter(user_id=data["id"]) # filter 返回对象
        jsonData = json.loads(serializers.serialize("json",userData))
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = jsonData
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)

@csrf_exempt # 允许跨域
@api_view(["POST"]) #
def getAllUserdata(request):
    '''
    获取所有用户信息
    '''
    try:
        userAllData = ptUser.objects.all()
        jsonData = json.loads(serializers.serialize("json",userAllData))
        for i in range(len(jsonData)):
            updataTime = jsonData[i]["fields"]["updata_time"]
            jsonData[i]["fields"]["updata_time"] = re.split('[TZ.]', updataTime)[0] + " " + re.split('[TZ.]', updataTime)[1]
            del jsonData[i]["fields"]["token"] # 删除重要数据 安全第一
            del jsonData[i]["fields"]["user_password"]
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = jsonData
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)

@csrf_exempt # 允许跨域
@api_view(["POST"]) #
def testAPI(request):
    '''
    testcase API
    '''
    try:
        userAllData = ptUser.objects.all()
        jsonData = json.loads(serializers.serialize("json",userAllData))
        for i in range(len(jsonData)):
            updataTime = jsonData[i]["fields"]["updata_time"]
            jsonData[i]["fields"]["updata_time"] = re.split('[TZ.]', updataTime)[0] + " " + re.split('[TZ.]', updataTime)[1]
            del jsonData[i]["fields"]["token"] # 删除重要数据 安全第一
            del jsonData[i]["fields"]["user_password"]
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = jsonData
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)


@csrf_exempt # 允许跨域
@api_view(["POST"]) #
def deleteUserdata(request):
    '''
    删除用户信息
    '''
    data = json.loads(request.body)
    try:
        ptUser.objects.get(user_id=data["id"]).delete()
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = response
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)
        response = httpResponseSignal.httpResponseSignal().getFail()
        return  JsonResponse(response)
